<?php
namespace App\Services;

use App\Enums\OrderStatusEnum;
use App\Models\OrderModel;
use App\Models\OrderPayModel;
use App\Models\ThirdUserModel;
use App\Models\UserModel;
use App\Support\CardParse;
use GuzzleHttp\Client;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Tymon\JWTAuth\Facades\JWTAuth;

class Check
{
    function login($type='miniapp',$code=''){
        if($type==='miniapp'){
            $data=KuaiShou::session($code);
            $openid=$data['openid']??'';
        }elseif($type==='h5'){
            $openid=md5(time().rand(1000,1000000));
        }else{
            abort(500,'未知登录类型');
        }
        return self::mlogin($openid,'',$type);
    }


    function orders($report=0,$size=15){
        $where=[
            'user_id'=>auth()->id()
        ];
        if($report){
            $where['status']=OrderStatusEnum::PAID;
        }
        $page=OrderModel::where($where)->orderBy('id','desc')->paginate($size);
        foreach($page->items() as $item){
            $item->setAppends(['code_str','status_str']);
            $item->setVisible(['sn','code_str','status_str','name','price','created_at','status','type']);
        }
        return $page;
    }

    function add($type,$name,$code){
        $sn='O'.date('ymdHis').rand(10000,99999);
        $config=config('check');
        if($type==1){
            $card=new CardParse($code);
            if(!$card->getVerify()){
                abort(400,'身份证号不合规');
            }
        }
        OrderModel::create([
            'sn'=>$sn,
            'type'=>$type,
            'name'=>$name,
            'code'=>$code,
            'price'=>$config['price']??29.9,
            'user_id'=>auth()->id()
        ]);
        return $sn;
    }

    function pay($sn,$type='miniapp'){
        return DB::transaction(function()use($sn,$type){
            $model=OrderModel::where('sn',$sn)->where('user_id',auth()->id())->lockForUpdate()->first();
            if(!$model){
                abort(500,'未知订单');
            }
            if($model->status){
                abort(500,'订单已支付');
            }
            $outNo='P'.date('ymdHis').rand(10000,99999);
            $openid='';
            if($type==='miniapp'){
                $openid=ThirdUserModel::where('user_id',$model->user_id)->where('platform',$type)->value('openid');
                if(!$openid){
                    abort(500,'未知用户');
                }
            }
            $pay=OrderPayModel::create([
                'amount'=>$model->price,
                'out_no'=>$outNo,
                'order_id'=>$model->id,
                'status'=>0,
                'user_id'=>$model->user_id,
                'openid'=>$openid
            ]);
            return MPay::pay($outNo,$pay->amount,'查询服务费');
        });

    }

    function payInfo($sn){
        return OrderModel::where('sn',$sn)->where('user_id',auth()->id())->select(['status'])->first();

    }

    function cancel($sn){
        $model=OrderModel::where('sn',$sn)->where('user_id',auth()->id())->first();
        if(!$model){
            abort(500,'未知订单');
        }
        if($model->status){
            abort(500,'订单已支付');
        }
        $model->delete();
    }

    protected function mlogin($openid,  $nickname, $type,$headImg='')
    {
        Log::info("login {$openid}  {$nickname} ");
        //是否存在openid
        $tuser = ThirdUserModel::where('openid', $openid)->where('platform', $type)->first();
        if ($tuser) {
            if ($user = $tuser->user) {
                if($headImg){
                    $user->head_img=$headImg;
                    $user->save();
                }
                return self::token($user);
            }
            abort(500, '登录失败，未知用户');
        }

        $user = DB::transaction(function () use ($openid, $nickname, $type,$headImg) {
            $user = UserModel::create([
                'mobile' => '',
                'nickname' => $nickname,
                'head_img'=>$headImg,
            ]);
            ThirdUserModel::create([
                'platform' => $type,
                'openid' => $openid,
                'unionid' => '',
                'user_id' => $user->id
            ]);
            return $user;

        });
        $user->refresh();
        return self::token($user);
    }

    function info($sn){
        $model=OrderModel::where('sn',$sn)->first();
        if(!$model){
            abort(500,'未知订单');
        }
        if($model->type==1){
            $card=new CardParse($model->code);
            return [
                'sn'=>$model->sn,
                'status'=>$model->status,
                'code'=>$model->code_str,
                'name'=>$model->name,
                'age'=>$card->getAge(),
                'grander'=>$card->getGrander(),
                'region'=>implode('',$card->getRegion()?:[]),
                'price'=>$model->price,
                'type'=>$model->type,
                'created_at'=>$model->created_at
            ];
        }
        return [
            'sn'=>$model->sn,
            'status'=>$model->status,
            'code'=>$model->code,
            'name'=>$model->name,
            'age'=>'',
            'grander'=>'',
            'region'=>'',
            'price'=>$model->price,
            'type'=>$model->type,
            'created_at'=>$model->created_at
        ];
    }

    // 司法
    static function sf($model)
    {
        $data=self::request($model);
        return $data['checkdata']??[];
    }

    // 失信
    static function sx($model)
    {
        $data=self::request($model,2);
        return $data['checkdata']??[];
    }

    // 消费
    static function xz($model)
    {
        $data=self::request($model,3);
        return $data['checkdata']??[];
    }

    static function hy($model){
        $hy=self::request($model,6);
        if($hy){
            return $hy['message']??'';
        }
        return '';
    }

    static function request($model,$type=1){
        $class='sf';
        if($type==5){
            $class='nameidc';
        }elseif($type==6){
            $class='hy';
        }elseif($type==7){
            $class='dtdk';
        }

        $config=config('check');
        $now=time();
        $nonceStr=md5($now);
        $param=[
            'orderno' => $nonceStr,
            'nonce_str' => $nonceStr,
            'name' => $model->name,
            'code' => $model->code,
            'datanumber' => 1,
            'detail' => 1,
            'serviceCode' => 'ALL',
            'classtype' => $class,  //接口类别，司法sf   nameidc证件验证   rlsb人脸识别    hy   dtdk
            'checktype' => $type,   //  1涉法涉案，2 失信  3 限制消费 ,4人脸识别  5姓名和身份证号匹配，6婚姻，7多头贷款
            'querytype' => $model->type,
            'client_ip' => request()->ip(),
            'isverifyrealname'=>1
        ];
        ksort($param);
        $singStr='';
        foreach($param as $k=>$item){
            $singStr.="{$k}={$item}&";
        }
        $sign="{$singStr}timestamp={$now}&secret={$config['secret']}";
        $sign=md5($sign);
        $client=new Client();
        $resp=$client->post('https://api.k-wz.com/api/goodcheckapi',[
            'headers'=>[
                'Content-type' => 'application/json',
                'X-Auth-Key' => $config['appkey'],
                'X-Auth-Sign' => $sign,
                'X-Auth-Timestamp' => $now
            ],
            'json'=>$param
        ]);
        if($resp->getStatusCode()===200){
            $data=json_decode($resp->getBody()->getContents(),true);
            Log::info('check '.$model->id,[$data]);
            if($data){
                $code=Arr::get($data,'code');
                if($code==1){
                    return Arr::get($data,'data');
                }
                $msg=Arr::get($data,'msg','未知错误');
                abort(500,"请求查询发生错误: {$msg}");
            }
        }
        abort(500,"请求查询发生错误: 网络原因");
    }

    static function token(UserModel $user = null)
    {
        if (!$user) {
            $user = auth()->user();
        }
        if ($user && $user->status) {
            if (!$user->sn) {
                $user->sn = md5(time() . rand(0, 100000));
            }
            $user->last_login = date('Y-m-d H:i:s');
            $user->save();
            return [
                'token' => 'Bearer ' . JWTAuth::fromUser($user),
                'expires' => auth('api')->factory()->getTTL() * 60,
                'sn' => $user->sn,
                'head_img' => $user->head_img,
            ];
        }
        abort(1401, '未知的用户');
    }

    static function payNotify($data){
        // {"out_no":"P25101411245037469","platform_no":"M251014112450267470","trade_no":"4200002829202510143665663500","amount":"0.01","paid_at":"2025-10-14 11:25:19","status":1}
        return DB::transaction(function()use($data){
            $outNo=$data['out_no']??'';
            $platformNo=$data['platform_no']??'';
            $status=$data['status']??0;
            if($status && $outNo && $platformNo){
                $model=OrderPayModel::where('out_no',$outNo)->first();
                if(!$model){
                    abort(500,'未知订单');
                }
                if($model->status){
                    return;
                }
                $model->status=1;
                $model->trade_no=$platformNo;
                $model->pay_at=date('Y-m-d H:i:s');
                if($model->save()){
                    $ret=OrderModel::where('id',$model->order_id)->update(['status'=>OrderStatusEnum::PAID]);
                    if(!$ret){
                        abort(500,'修改订单状态失败');
                    }
                }else{
                    abort(500,'修改支付状态失败');
                }
            }
        });
    }
}
